use async_std::fs::File;
use async_std::io;
use std::io::Write;
use async_std::io::BufReader;
use async_std::prelude::*;
use async_std::task;
use serial_raw::tty::TTYPort;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path::Path;
use std::env;

async fn hello_uart(path: &str) {
    let pth = Path::new(path);
    let p = TTYPort::open(&pth, 115200).unwrap();
    let mut writer = p.clone();
    let reader = unsafe {BufReader::new(File::from_raw_fd(p.as_raw_fd()))};

    let _read_task = task::spawn(async {
        let mut lines = reader.lines();

        while let Some(line) = lines.next().await {
            let line = line.unwrap();

            println!("{}", line);
        }
    });

    loop {
        let mut input = String::new();

        io::stdin().read_line(&mut input).await.unwrap();
        writer.write(input.as_bytes()).unwrap();
        writer.flush().unwrap();
    }
}

fn main() {
    let t = task::spawn(async {
        let args: Vec<String> = env::args().collect();
        let port = &args[1];
        hello_uart(port).await;
    });

    task::block_on(t);
}
